package org.diffshop.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.diffshop.common.enums.BizCodeEnum;
import org.diffshop.common.utils.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:tjf
 * @Description:
 */
@Slf4j
@RestControllerAdvice(basePackages = {"org.diffshop.product.controller", "org.diffshop.coupon.controller"})
public class DiffshopExceptionAdvice {
    /**
     * 统一处理方法参数未校验通过异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出错{},参数类型{}", e.getMessage(), e.getClass());
        Map<String, String> errMap = new HashMap<>();
        // 将所有的字段错误封装在map中
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("err", errMap);
    }
    @ExceptionHandler(RRException.class)
    public R handleRRException(RRException e){
        return R.error(e.getCode(), e.getMsg());
    }
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION).put("err", throwable.getMessage());
    }
}
